package com.orkun.api.converter.writer;

import nu.xom.*;

import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import com.orkun.api.converter.impl.AddressInfoModel;
import com.orkun.api.converter.utils.Utility;

/**
 * XML writer implementation for AddressInfoModel
 * Ext Lib ref: http://www.xom.nu/tutorial.xhtml
 */
public class WriterXML implements Writer<AddressInfoModel> {

  public void output(OutputStream os, ArrayList<AddressInfoModel> models) {


    Element root = new Element(AddressInfoModel.ADDRESS_INFO);
    for (AddressInfoModel model : models) {
      Element city = new Element(AddressInfoModel.CITY);
      Attribute cityname =
          new Attribute(AddressInfoModel.NAME, String.valueOf(model.getCityName()));
      city.addAttribute(cityname);
      Attribute citycode =
          new Attribute(AddressInfoModel.CODE, String.valueOf(model.getCityCode()));
      city.addAttribute(citycode);

      Element district = new Element(AddressInfoModel.DISTRICT);
      Attribute distname =
          new Attribute(AddressInfoModel.NAME, String.valueOf(model.getDistrictName()));
      district.addAttribute(distname);

      Element zip = new Element(AddressInfoModel.ZIP);
      Attribute zipcode = new Attribute(AddressInfoModel.CODE, String.valueOf(model.getZipCode()));
      zip.addAttribute(zipcode);

      district.appendChild(zip);
      city.appendChild(district);
      root.appendChild(city);
    }
    Document doc = new Document(root);

    try {
      Serializer serializer = new Serializer(os, Utility.getEncoding().toString());
      serializer.setIndent(4);
      serializer.setMaxLength(64);
      serializer.write(doc);
    } catch (IOException ex) {
      System.err.println(ex);
    }
  }
}
